import React from 'react';
import {Table, message as msg} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PAGINATION_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, DATETIME_FORMAT} from '../constants';
import {PERMISSION} from './constants';
import {injectIntl, language} from './intl';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {hasPermissions} from './utils';
import {repairType, claimApplyStatus} from '../Enum';
import {abandonData, submitData, returnData} from './api';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import DropdownMenu from 'Shared/components/DropdownMenu';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
const basePath = fetch.basePath || '';
const url = '/#/dcs/afterSales/claim/add';
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }

    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    onClickSubmitBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        submitData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onClickAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        abandonData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onClickReturnBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        returnData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onClickApprove = e => {
        const {id} = e.target.dataset;
        const record = this.props.list.find(d => d.id === id);
        if(record.isExistsExchangeRate === true)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.isExistsExchangeRateTrue',
                defaultMessage: '预申请单币种与美元存在多条有效的汇率信息，请维护后再审核'
            }));
        if(record.isExistsExchangeRate === false)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.isAllowApproveFales',
                defaultMessage: '预申请单币种与美元不存在 汇率信息，请维护后再审核'
            }));
        if(!record.isAllowApprove)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.isAllowApprove',
                defaultMessage: '多级审核配置不正确'
            }));
        this.props.history.push(routes.approve.format(id));
    }
    render() {
        const languageIntl = language;
        const colums = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '预授权单号'
                }),
                dataIndex: 'code',
                width: languageIntl === 'pt-PT' ? 260 : 190,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
                render: (text, record) => <Link to={routes.detail.format(record.id)} >{text}</Link>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                width: languageIntl === 'pt-PT' ? 150 : 120,
                render: text => conventEnumValueToString(claimApplyStatus, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.repairCode',
                    defaultMessage: '维修单号'
                }),
                dataIndex: 'repairCode',
                width: languageIntl === 'pt-PT' ? 260 : 190,
                render: text => <span title={text}><Ellipsis length={20}>{text}</Ellipsis></span>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.subDealerCode',
                    defaultMessage: '经销商编号'
                }),
                dataIndex: 'subDealerCode',
                width: languageIntl === 'pt-PT' ? 260 : 190,
                render: text => <span title={text}><Ellipsis length={20}>{text}</Ellipsis></span>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.causePartCode',
                    defaultMessage: '主损件编号'
                }),
                dataIndex: 'causePartCode',
                width: languageIntl === 'pt-PT' ? 260 : 195,
                render: text => <span title={text}><Ellipsis length={20}>{text}</Ellipsis></span>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.causePartName',
                    defaultMessage: '主损件名称'
                }),
                dataIndex: 'causePartName',
                width: 280,
                render: text => <span title={text}><Ellipsis length={20}>{text}</Ellipsis></span>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.vin',
                    defaultMessage: 'VIN'
                }),
                dataIndex: 'vin',
                width: 170,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'vin' && this.props.sortedOrder
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.productCategoryCode',
                    defaultMessage: '车型'
                }),
                dataIndex: 'productCategoryCode',
                width: languageIntl === 'pt-PT' ? 170 : 150,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'productCategoryCode' && this.props.sortedOrder
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.isKD',
                    defaultMessage: 'CBU/KD'
                }),
                width: 100,
                dataIndex: 'isKD'
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.repairType',
                    defaultMessage: '索赔类型'
                }),
                dataIndex: 'repairType',
                width: languageIntl === 'pt-PT' ? 180 : 150,
                render: text => conventEnumValueToString(repairType, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.createTime',
                    defaultMessage: '创建时间'
                }),
                dataIndex: 'createTime',
                width: 180,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'createTime' && this.props.sortedOrder,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.submitTime',
                    defaultMessage: '提交时间'
                }),
                dataIndex: 'submitTime',
                width: 180,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'submitTime' && this.props.sortedOrder,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.approveTime',
                    defaultMessage: '审核时间'
                }),
                dataIndex: 'approveTime',
                width: 180,
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'approveTime' && this.props.sortedOrder,
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }];
        if(!this.props.isDealerUser) {
            colums.splice(0, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.dealer',
                        defaultMessage: '总代'
                    }),
                    dataIndex: 'dealerCode',
                    width: 100,
                    sorter: true,
                    sortOrder: this.props.sortedColumnKey === 'dealerCode' && this.props.sortedOrder
                }
            ]);
            colums.splice(13, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.countersigner',
                        defaultMessage: '会签人'
                    }),
                    dataIndex: 'countersigner',
                    width: 100,
                }, {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.isCountersign',
                        defaultMessage: '是否会签'
                    }),
                    dataIndex: 'isCountersign',
                    width: 100,
                    render: text => text ? this.props.intl.formatMessage({
                        id: 'tablePanel.column.y',
                        defaultMessage: '是'
                    }) : this.props.intl.formatMessage({
                        id: 'tablePanel.column.n',
                        defaultMessage: '否'
                    }),
                }
            ]);
        }
        if(!this.props.isMoneyVisible)
            colums.splice(11, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.totalFee',
                        defaultMessage: '费用合计'
                    }),
                    dataIndex: 'totalFee',
                    width: 100,
                    render: text => formatAmount(text)
                }
            ]);
        colums.push({
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.operation',
                defaultMessage: '操作'
            }),
            dataIndex: 'id',
            key: 'id',
            width: 130,
            fixed: 'right',
            render: (text, r) => {
                const menus = [{
                    id: PERMISSION.update,
                    children: <Link key="update" to={routes.update.format(r.id)}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.update',
                            defaultMessage: '编辑'
                        })
                    }</Link>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update)),
                }, {
                    id: PERMISSION.approve,
                    children: <a key="approve" data-id={r.id} onClick={this.onClickApprove}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.approve',
                            defaultMessage: '审核'
                        })
                    }</a>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(r.options, PERMISSION.approve)),
                }, {
                    id: PERMISSION.adjust,
                    children: <Link key="adjust" to={routes.adjust.format(r.id)}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.adjust',
                            defaultMessage: '调整'
                        })
                    }</Link>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.adjust) && hasPermissions(r.options, PERMISSION.adjust)),
                }, {
                    id: PERMISSION.countersigner,
                    children: <Link key="update" to={routes.countersigner.format(r.id)}>{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.countersigner',
                            defaultMessage: '会签'
                        })
                    }</Link>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.countersigner) && hasPermissions(r.options, PERMISSION.countersigner)),
                }, {
                    id: PERMISSION.abandon,
                    children: (ref =>
                        <WrappedPopconfirm
                            key="abandon"
                            placement="topLeft"
                            onConfirm={this.onClickAbandonBtn}
                            id={r.id}
                            onVisibleChange={ref.setMenuVisible}
                            title={this.props.intl.formatMessage({
                                id: 'tablePanel.validate.abandon',
                                defaultMessage: '是否确认作废？'
                            })}>
                            <a>{
                                this.props.intl.formatMessage({
                                    id: 'tablePanel.abandon',
                                    defaultMessage: '作废'
                                })
                            }</a>
                        </WrappedPopconfirm>
                    ),
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon)),
                }, {
                    id: PERMISSION.claim,
                    children: <a href={`${basePath}${url}?id=${r.id}`} target="_blank" rel="noopener noreferrer">{
                        this.props.intl.formatMessage({
                            id: 'tablePanel.operation.claim',
                            defaultMessage: '索赔'
                        })
                    }</a>,
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.claim) && hasPermissions(r.options, PERMISSION.claim)),
                }];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        });
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={colums}
                    dataSource={this.props.list}
                    onChange={this.onChangeSort}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading || this.state.loading}
                    locale={locale}
                    scroll={{
                        x: 'max-content',
                        y: 540}}
                    size="small"
                    bordered={true} />
            </div>
        );
    }
}

TablePanel.propTypes = {
    errorMessage: PropTypes.string.isRequired,
    list: PropTypes.array.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    isMoneyVisible: PropTypes.bool,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    refreshListData: PropTypes.func,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    list: getData(state),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    isMoneyVisible: state.getIn((['page', 'domainData', 'initData', 'isMoneyVisible'])),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch())
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
